package com.b1502.store2.fragment;


import android.content.Intent;

import android.os.Bundle;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;


import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import android.widget.Button;
import android.widget.CheckBox;


import android.widget.CompoundButton;
import android.widget.TextView;


import android.widget.Toast;

import com.b1502.store2.R;


import com.b1502.store2.StoreApp;


import com.b1502.store2.activity.ConfirmOrderActivity;
import com.b1502.store2.adapter.CartAdapter;
import com.b1502.store2.adapter.HomeProductAdapter;

import com.b1502.store2.model.bean.CartBean;
import com.b1502.store2.model.bean.HomeProductsBean;


import com.b1502.store2.model.bean.OrderBean;
import com.b1502.store2.network.PostParams;
import com.b1502.store2.network.StoreParams;
import com.b1502.store2.util.UrlUtil;

import com.b1502.store2.widget.StoreBar;
import com.google.gson.Gson;


import org.mym.plog.PLog;
import org.xutils.common.Callback;
import org.xutils.x;

/**
 * A
 * simple {@link Fragment} subclass.
 * Use
 * the
 * {@link CartFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public
class
CartFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    private View inflate;


    private RecyclerView recyclerView;


    private CartAdapter cartAdapter;

    private CartBean[] cartBeen;


    private CheckBox checkBox;


    private TextView all_price;


    private Button jiesuan;


    private Button bianji;


    public CartFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment CartFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static CartFragment newInstance(String param1, String param2) {
        CartFragment fragment = new CartFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        inflate = inflater.inflate(R.layout.fragment_cart, container, false);

        return inflate;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        all_price = (TextView) inflate.findViewById(R.id.all_price);
        jiesuan = (Button) inflate.findViewById(R.id.jiesuan);
        checkBox = (CheckBox) inflate.findViewById(R.id.all_check);
        recyclerView = (RecyclerView) inflate.findViewById(R.id.cart_RecyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        bianji = (Button) inflate.findViewById(R.id.bianji);
        getItems();

    }

    //处理购物车中的逻辑
    private void onClickListener() {

        cartAdapter.setOnClikerListener(new CartAdapter.OnClikerListener() {

            //处理单个复选框逻辑
            @Override
            public void checkBoxListener(int position, boolean isChecked) {

                if (isChecked) {

                    cartBeen[position].setCheck(isChecked);

                } else {

                    cartBeen[position].setCheck(isChecked);
                }
                countPrice();
            }

            //处理删除逻辑
            @Override
            public void deleteListener(int position) {

                removeItems("productId", cartBeen[position].getProductId());


            }

            //处理增减商品逻辑
            @Override
            public void jianListener(int position) {

                if (cartBeen[position].getCount() > 1) {
                    int i = (cartBeen[position].getCount()) - 1;
                    cartBeen[position].setCount(i);
                } else {
                    Toast.makeText(getActivity(), "亲，不能再少了哦！", Toast.LENGTH_SHORT).show();
                }
                cartAdapter.notifyDataSetChanged();
                countPrice();

            }

            //处理增减商品逻辑
            @Override
            public void jiaListener(int position) {

                int i = (cartBeen[position].getCount()) + 1;
                cartBeen[position].setCount(i);
                cartAdapter.notifyDataSetChanged();
                countPrice();
            }
        });


        //处理子条目的点击事件
        cartAdapter.setOnItemClickListener(new CartAdapter.OnRecyclerViewItemClickListener() {

            @Override
            public void onItemClick(View view, int position) {


            }
        });

        //处理全选逻辑
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {
                    for (int i = 0; i < cartBeen.length; i++) {


                        cartBeen[i].setCheck(true);

                    }
                } else {

                    for (int i = 0; i < cartBeen.length; i++) {

                        cartBeen[i].setCheck(false);

                    }
                }
                countPrice();
                cartAdapter.notifyDataSetChanged();
            }
        });

        //处理结算按钮
        jiesuan.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                int num = 0;
                for (int i = 0; i < cartBeen.length; i++) {

                    if (cartBeen[i].isCheck()) {

                        num += 1;
                    }

                }

                String[] strings = new String[num];
                int[] ints = new int[num];
                int count = 0;
                for (int i = 0; i < cartBeen.length; i++) {
                    if (cartBeen[i].isCheck()) {

                        strings[count] = cartBeen[i].getProductId();
                        ints[count] = cartBeen[i].getCount();
                        count++;
                    }

                }
                if(strings.length>0){

                //请求创建订单数据
                String[] productIds = strings;
                int[] quantities = ints;
                    //PLog.e(productIds[0]);
                createOrder(productIds, quantities);

                }else {
                    Toast.makeText(getActivity(),"请您先去选商品",Toast.LENGTH_SHORT).show();
                    return;
                }

            }
        });
        //处理编辑逻辑
        bianji.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (!StoreApp.flag) {

                    StoreApp.flag = true;
                    bianji.setText("完成");
                } else {

                    StoreApp.flag = false;
                    bianji.setText("编辑");
                }

                cartAdapter.notifyDataSetChanged();

            }
        });

    }

    //计算价格
    public void countPrice() {

        double num = 0;
        int count = 0;
        //遍历所有商品
        for (int i = 0; i < cartBeen.length; i++) {
            //计算选中商品的价格及数量
            if (cartBeen[i].isCheck()) {

                num = num + (cartBeen[i].getPrice() * cartBeen[i].getCount());

                count = count + cartBeen[i].getCount();
            }

        }
        float c= (float) num;

        all_price.setText("￥" + c);
        jiesuan.setText("结算" + count);
    }

    //处理购物车删除逻辑
    private void removeItems(String param, String productId) {

        StoreParams params = new StoreParams(UrlUtil.RemoveItems, param, productId);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onSuccess(String result) {

                //PLog.e(result);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //处理购物车数据
    private void getItems() {

        StoreParams params = new StoreParams(UrlUtil.GetItems);

        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onSuccess(String result) {

                CartBean[] cartBeen1 = new Gson().fromJson(result, CartBean[].class);
                cartBeen = cartBeen1;
                cartAdapter = new CartAdapter(cartBeen, getActivity());
                recyclerView.setAdapter(cartAdapter);
                onClickListener();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 创建订单
     *
     * @param productIds 商品ID集合
     * @param quantities 商品数量
     */
    public void createOrder(String[] productIds, int[] quantities) {
        StoreParams params = new StoreParams(UrlUtil.CreateOrder);
        params.setAsJsonContent(true);
        PostParams postParams = new PostParams(productIds, quantities);
        params.setBodyContent(new Gson().toJson(postParams));

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onSuccess(String result) {
                //TODO 跳转到确认订单
                //PLog.e(result);
                OrderBean orderBean = new Gson().fromJson(result, OrderBean.class);
                Intent intent=new Intent(getActivity(), ConfirmOrderActivity.class);
                intent.putExtra("orderId",orderBean.Id);
                getActivity().startActivity(intent);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


}
